<?php

namespace EthanZ\LaravelExt\Utils\Tools;

/**
 * 数组工具类
 */
class ArrTools
{


    /**
     * 数组转树形结构
     *
     * @param array      $list
     * @param int|string $pid
     * @param string     $pidField
     * @param string     $pkField
     * @param string     $childrenName
     * @param int        $level
     *
     * @return array
     */
    public static function arrToTree(
        array      &$list,
        int|string $pid = 0,
        string     $pidField = 'pid',
        string     $pkField = 'id',
        string     $childrenName = 'children',
        int        $level = 1
    ): array
    {
        $data = [];
        foreach ($list as $k => $val) {
            if (!isset($val[$pidField], $val[$pkField])) {
                continue;
            }

            if ($val[$pidField] === $pid) {
                $temp   = $val + [
                        'level'       => $level,
                        $childrenName => self::arrToTree(
                            $list,
                            $val[$pkField],
                            $pidField,
                            $pkField,
                            $childrenName,
                            $level + 1
                        ),
                    ];
                $data[] = $temp;
                unset($list[$k]);
            }
        }

        return $data;
    }


    /**
     * 树形结构转数组
     *
     * @param array  $tree
     * @param string $childrenName
     * @param int    $level
     * @param array  $arr
     *
     * @return array
     */
    public static function treeToArr(
        array  $tree,
        string $childrenName = 'children',
        int    $level = 1,
        array  &$arr = []
    ): array
    {
        foreach ($tree as $val) {
            $children = $val[$childrenName] ?? [];
            unset($val[$childrenName]);
            $arr[] = array_merge($val, ['level' => $level]);
            if ($children) {
                self::treeToArr($children, $childrenName, $level + 1, $arr);
            }
        }

        return $arr;
    }
}
